<template>
  <div class="chat-window">
    <!-- 消息列表 -->
    <div class="message-list" ref="messageList">
      <div v-for="(msg, index) in sortedMessages" :key="index" class="message-item" :class="{
        'self-message': msg.fromUserId === userInfo.userId,
        'other-message': msg.fromUserId !== userInfo.userId
      }">
        <!-- 对方消息（左对齐） -->
        <template v-if="msg.fromUserId !== userInfo.userId">
          <el-avatar :size="40" :src="userRelatedMessageResp.avatar || ''" class="avatar"></el-avatar>
          <div class="message-content">
            <div class="message-bubble other-bubble">
              {{ msg.message }}
              <div class="message-time-other">{{ formatTime(msg.createdAt) }}</div>
            </div>
          </div>
        </template>

        <!-- 自己消息（右对齐） -->
        <template v-else>
          <div class="message-content">
            <div class="message-bubble self-bubble">
              {{ msg.message }}
              <div class="message-time-self">{{ formatTime(msg.createdAt) }}</div>
            </div>
          </div>
          <el-avatar :size="40" :src="userInfo.avatar || ''" class="avatar"></el-avatar>
        </template>
      </div>
    </div>

    <deliveryWindow :id="toUserId" v-if="deliveryVisible" @close="deliveryVisible = false" :visible="deliveryVisible" />

    <!-- 输入区域 -->
    <div class="chat-input-area">
      <!-- 附件、快捷按钮区 -->
      <div class="input-actions">
        <button class="action-btn">
          <i class="el-icon-picture-outline-round"></i>
        </button>
        <button class="action-btn">
          <i class="el-icon-picture-outline"></i>
        </button>
        <button class="action-btn" @click="delivery" v-if="userType === 'seeker'">投递</button>
        <button class="action-btn">换电话</button>
        <button class="action-btn">换微信</button>
      </div>
      <!-- 输入框 + 发送按钮 -->
      <div class="input-control">
        <input v-model="inputValue" placeholder="输入消息..." @keyup.enter="handleSend" class="message-input" />
        <button @click="handleSend" class="send-btn">发送</button>
      </div>
    </div>
  </div>
</template>

<script>
import { formatTime } from '@/util/get-time'
import { mapState } from 'vuex'
import DeliveryWindow from '@/components/chat/deliveryWindow.vue'

export default {
  name: 'ChatWindow',
  components: {
    DeliveryWindow
  },
  props: {
    messages: { type: Array, default: () => [] },
    toUserId: { type: Number, default: null },
    userRelatedMessageResp: { type: Object, default: () => { } },
    userType: { type: String, default: null }
  },
  data() {
    return {
      inputValue: '',
      deliveryVisible: false
    }
  },
  computed: {
    sortedMessages() {
      return this.messages.sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt))
    },
    userInfo() {
      const module = this.userType === 'seeker' ? 'seeker' : 'recruiter'
      return this.$store.state[module]?.userInfo || { userId: null, avatar: '' }
    }
  },
  methods: {
    showTimestamp(index) {
      if (index === 0) return true
      const currentTime = new Date(this.sortedMessages[index].createdAt)
      const prevTime = new Date(this.sortedMessages[index - 1].createdAt)
      return (currentTime - prevTime) / (1000 * 60) > 10
    },
    formatTime(timestamp) {
      const date = new Date(timestamp)
      const now = new Date()
      if (date.toDateString() === now.toDateString()) {
        return date.toTimeString().substring(0, 5)
      }
      if (date.getFullYear() === now.getFullYear()) {
        return `${date.getMonth() + 1}/${date.getDate()} ${date.toTimeString().substring(0, 5)}`
      }
      return date.toLocaleString()
    },
    handleSend() {
      if (!this.inputValue.trim()) return
      this.$emit('sendMessage', this.inputValue.trim(), this.toUserId)
      this.inputValue = ''
    },
    delivery() {
      this.deliveryVisible = true;
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.$refs.messageList.scrollTop = this.$refs.messageList.scrollHeight
    })
  },
  watch: {
    messages() {
      this.$nextTick(() => {
        this.$refs.messageList.scrollTop = this.$refs.messageList.scrollHeight
      })
    }
  }
}
</script>

<style scoped>
.chat-window {
  width: 100%;
  height: 580px;
  display: flex;
  flex-direction: column;
  border: 1px solid #e5e5e5;
  border-radius: 8px;
  /* overflow: hidden; */
}

.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  background-color: #f9fafc;
}

.message-item {
  display: flex;
  margin-bottom: 16px;
  align-items: flex-start;
}

/* 自己的消息（右对齐） */
.self-message {
  justify-content: flex-end;
}

/* 对方的消息（左对齐） */
.other-message {
  justify-content: flex-start;
}

.avatar {
  margin: 0 8px;
}

.message-content {
  max-width: 70%;
}

.message-bubble {
  padding: 10px 14px;
  border-radius: 8px;
  position: relative;
  word-wrap: break-word;
  margin: 5px 8px;
}

/* 对方消息气泡样式 */
.other-bubble {
  background-color: #fff;
  border: 1px solid #e5e5e5;
  color: #333;
  border-bottom-left-radius: 2px;
  /* 优化圆角 */
}

/* 自己消息气泡样式 */
.self-bubble {
  background-color: #41968d;
  color: #fff;
  border-bottom-right-radius: 2px;
  /* 优化圆角 */
}

.message-time-self {
  font-size: 12px;
  color: #999;
  position: absolute;
  bottom: -20px;
  right: 10px;
}

.message-time-other {
  font-size: 12px;
  color: #999;
  position: absolute;
  bottom: -20px;
  left: 10px;
}

.message-timestamp {
  margin: 8px 0;
}

.chat-input-area {
  height: 30%;
  border-top: 1px solid #eee;
  padding: 8px 12px;
  background: #f9fafc;
}

.input-actions {
  display: flex;
  gap: 8px;
  margin-right: 12px;
}

.action-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 6px 10px;
  cursor: pointer;
  font-size: 14px;
}

.action-btn img {
  width: 18px;
  height: 18px;
}

.input-control {
  width: 100%;
  display: flex;
  flex: 1;
  height: 100%;
}

.message-input {
  flex: 1;
  padding: 8px;
  border: currentColor;
  border-radius: 4px 0 0 4px;
  outline: none;
  background: none;
}

.send-btn {
  background: #41968d;
  color: #fff;
  border: none;
  border-radius: 4px;
  padding: 8px 16px;
  cursor: pointer;
  height: 35px;
  margin-top: 75px
}


/* 滚动条样式 */
.message-list::-webkit-scrollbar {
  width: 6px;
}

.message-list::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.message-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

.message-list::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>